import { fabric } from "fabric";

fabric.LineArrow = fabric.util.createClass(fabric.Line, {
    type: "LineArrow",
    initialize: function (points, options) {
        options || (options = {})
        // 配置当前对象附件属性
        this.set({
            arrowLen:options.arrowLen || 50,
        })
        // 传递参数options
        this.callSuper('initialize', points, options)
    },
    _render: function(ctx) {
        this.callSuper('_render', ctx)
        // 重新计算给定宽度和高度的线点
        const { x1, y1, x2, y2 } = this.calcLinePoints();
        /**
         * 计算原点(0,0)到(x,y)点的线段与x轴正方向之间的平面角度 (弧度值)
         * @see {@link https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Math/atan2}
         */
        const angle = Math.atan2(y2 - y1, x2 - x1);
        // 设置箭头长度 50
        const headLen = this.arrowLen
        // 计算终点坐标和x轴正向夹角
        ctx.beginPath()
        ctx.moveTo(x1, y1)
        // 绘制箭头的主干线终点坐标
        ctx.lineTo(x2, y2)

        // 计算并绘制箭头头部左侧，逆时针-30度
        const leftX = x2 - headLen * Math.cos(angle - Math.PI/6)
        const leftY = y2 - headLen * Math.sin(angle - Math.PI/6)
        // 计算并绘制见偷偷头部右侧，顺时针+30度
        const rightX = x2 - headLen * Math.cos(angle + Math.PI/6)
        const rightY = y2 - headLen * Math.sin(angle + Math.PI/6)

        // 1、从终点出发绘制，线条箭头
        ctx.moveTo(x2, y2)
        ctx.lineTo(leftX, leftY)
        ctx.moveTo(x2, y2)
        ctx.lineTo(rightX, rightY)
        ctx.fillStyle = this.fill || "#FDFFE2";
        ctx.fill()
        ctx.strokeStyle = this.stroke || "#83B4FF";
        ctx.stroke()
        // ctx.lineWidth = 1
        // ctx.fill()
        ctx.closePath()
    }
})

// 增加fromObject方法，避免撤销操作报错
fabric.LineArrow.fromObject = (options, callback) => {
    const { x1, x2, y1, y2 } = options;
    return callback(new fabric.LineArrow([x1, y1, x2, y2], options));
};

export default fabric.LineArrow;